package com.testing.login;

import com.testing.sqlUtil.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Classname ${NAME}
 * @Description 类型说明
 * @Date 2021/1/5 22:03
 * @Created by 特斯汀Roy
 */
@WebServlet(name = "GetUserInfo")
public class GetUserInfo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        //判断session中是否已经记录了登录用户的信息
        if(request.getSession().getAttribute("loginName")!=null){
            //已经登录
            //从session中获取记录的用户名，用于完成用户信息的查询。
            MysqlUtils roy=new MysqlUtils();
            roy.createConnector();
            Map<String, String> userinfoMap = roy.getUserinfo(request.getSession().getAttribute("loginName").toString());
            String jsonResult="{";
            for(String key:userinfoMap.keySet()){
                //用户名密码不返回
                if(!key.equals("password")&&!key.equals("username")){
                    jsonResult+= "\""+key+"\":\""+userinfoMap.get(key)+"\",";
                }
            }
            jsonResult+="}";
            jsonResult=jsonResult.replaceAll(",}","}");
            response.getWriter().append(jsonResult);
        }
        else{
            //没有登录
            response.getWriter().append("{\"status\":-1,\"msg\":\"" + "您还没没有登录，不能查询用户信息" + "\"}");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("{\"status\":-1,\"msg\":\"" + "不支持使用get方法进行用户信息查询" + "\"}");
    }
}
